<?php
//include_once('./conn.php');
class MMsql{
	protected static $_dbh = null;
	protected $_sql  = '';
	protected $_host = 'l4li1apk.2318.dnstoo.com';
	protected $_port = 5509;
	protected $_user = 'huzhew_f';
	protected $_pass = 'huzhewang';
	protected $_dbName = 'huzhew'; //数据库名
	protected $_dbType = 'mysql';
	protected $_pconnect = true; //是否使用长连接
	protected $_trans = 0; //事务指令数
	
	
	
	public function __construct(){
		//echo $this->_host;
		$this->_connect();
	}
	protected function _connect(){
		$dsn = $this->_dbType.':host='.$this->_host.';port='.$this->_port.';dbname='.$this->_dbName;
		$options = $this->_pconnect ? array(PDO::ATTR_PERSISTENT=>true) : array();
		try { 
		    $dbh = new PDO($dsn, $this->_user, $this->_pass, $options);
		    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  //设置如果sql语句执行错误则抛出异常，事务会自动回滚
		    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //禁用prepared statements的仿真效果(防SQL注入)
		} catch (PDOException $e) { 
		    die('Connection failed: ' . $e->getMessage());
		}
		$dbh->exec('SET NAMES utf8');
		self::$_dbh = $dbh;
		// $link=mysqli_connect($this->_host.":".$this->_port,$this->_user,$this->_pass,$this->_dbName) ;
		// if(mysqli_connect_errno()){
		// 	die('Connection Error：'.mysqli_connect_errno());
		// }
		// //2、设置字符集
		// mysqli_set_charset($link,'utf8');
		// date_default_timezone_set("PRC");//东八区时间设置
		//$this->_link=$link;
	}
	/**
	* 执行查询 mysqli_query
	*/
	// public function dosql($sql=''){
	// 	$result=mysqli_query($this->_link,$sql);
	// 	$list=array();
	// 	if(!empty($result)){
	// 		while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
	// 			$list[]=$row;//将取得的所有数据，一行两行或者三行
	// 		}
	// 	}
	// 	return $list;
	// }
	/**
	* 执行查询 主要针对 SELECT, SHOW 等指令
	* @param string $sql sql指令 
	* @return mixed 
	*/
	protected function _doQuery($sql='') {
	    $this->_sql = $sql;
	    $pdostmt = self::$_dbh->prepare($this->_sql); //prepare或者query 返回一个PDOStatement
	    $pdostmt->execute();
	    $result = $pdostmt->fetchAll(PDO::FETCH_ASSOC);
	    return $result;
	}
	/**
	* 执行语句 针对 INSERT, UPDATE 以及DELETE,exec结果返回受影响的行数
	* @param string $sql sql指令 
	* @return integer 
	*/
	protected function _doExec($sql='') {
	    $this->_sql = $sql;
	    return self::$_dbh->exec($sql);
	}
	/**
	 * 格式化键值对
	*/
	public function formatVal($dataArr){
		$ret=Array();
		foreach($dataArr as $key=>$val){
			$val = '"'.addslashes($val).'"';//$val = "'".".$val."."'";
			$ret[$key]=$val;
		}
		return $ret;
	}
	/**
	* 执行sql语句，自动判断进行查询或者执行操作 
	* @param string $sql SQL指令 
	* @return mixed 
	*/
	public function doSql($sql) {
	    $queryIps = 'INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOAD DATA|SELECT .* INTO|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK'; 
	    if (preg_match('/^\s*"?(' . $queryIps . ')\s+/i', $sql)) { 
	        return $this->_doExec($sql);
	    }
	    else {
	        //查询操作
	        return $this->_doQuery($sql);
	    }
	}
	 
	public function insert($tbName,array $data){
	    $data = $this->_dataFormat($tbName,$data);
	    if (!$data) return;
	    $sql = "insert into ".$tbName."(".implode(',',array_keys($data)).") values(".implode(',',array_values($data)).")";
	    return $this->_doExec($sql);
	}
	/**
	* 启动事务 
	* @return void 
	*/
	public function startTrans() { 
	    //数据rollback 支持 
	    if ($this->_trans==0) self::$_dbh->beginTransaction();
	    $this->_trans++; 
	    return; 
	}
	/**
	* 用于非自动提交状态下面的查询提交 
	* @return boolen 
	*/
	public function commit() {
	    $result = true;
	    if ($this->_trans>0) { 
	        $result = self::$_dbh->commit(); 
	        $this->_trans = 0;
	    } 
	    return $result;
	}
	/**
	* 事务回滚 
	* @return boolen 
	*/
	public function rollback() {
	    $result = true;
	    if ($this->_trans>0) {
	        $result = self::$_dbh->rollback();
	        $this->_trans = 0;
	    }
	    return $result;
	}
	 
    /**
    * 关闭连接
    * PHP 在脚本结束时会自动关闭连接。
    */
    public function close() {
        if (!is_null(self::$_dbh)) self::$_dbh = null;
    }
	
}